package com.woniu.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBufAllocator;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

/**
 * 全局过滤器
 */
@Slf4j
public class FinanceGlobalFilter implements GlobalFilter, Ordered {

    private final ObjectMapper mapper = new ObjectMapper();
    private final DataBufferFactory dataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        log.debug("Method:{}", request.getMethod());
        String uri = request.getURI().toString();
        log.debug("URI:{}", uri);
        log.debug("Path:{}", request.getPath());
        log.debug("QueryParams:{}", request.getQueryParams());
        request.getHeaders().keySet().forEach(key -> {
            log.debug("请求头信息 - k:{} , v:{}", key, request.getHeaders().get(key));
        });
        /*int api = uri.indexOf("v2/api-docs");
        String path =request.getPath().toString();
        if(api==-1){//拦截非swagger的api的请求
            if (path.equals("登录请求") || path.equals("注册请求")) {
                // 放行登录注册请求
                return chain.filter(exchange);
            } else {
                //获取请求头中的token信息
                String token = request.getHeaders().getFirst("token");
                //解析token
                if(){//token正确，放行
                    return chain.filter(exchange);
                }
                // token错误，拒绝路由。
                String jsonStr = "{\"status\":\"-1\",\"msg\":\"error\"}";
                byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
                return exchange.getResponse().writeWith(Flux.just(buffer));
            }
        }else{
            //放过所有swagger的api
            log.info("swagger的api：{}",uri);
            return chain.filter(exchange);
        }*/

        log.info("目标微服务【执行前】执行");
        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    log.info("目标微服务【执行后】执行");
                }));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}